package com.baishui.gateway.clazzsouce;

import com.baishui.gateway.classloader.GateWayClassLoader;
import com.baishui.gateway.utils.JarHelper;
import com.baishui.gateway.utils.StringUtilsExt;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public abstract class ClazzSource {

    public static GateWayClassLoader readJars() {
        GateWayClassLoader instance = GateWayClassLoader.getInstance();
        try {
            URL url = ClazzSource.class.getClassLoader().getResource("jar/dubbo-demo" +
                    "-interface-2.7.7.jar");
            JarFile jarFile = new JarFile(new File(url.getPath()));
            Enumeration<JarEntry> entries = jarFile.entries();
            while (entries.hasMoreElements()) {
                JarEntry jarEntry = entries.nextElement();
                if (jarEntry.getName().endsWith(".class")) {
                    String className = jarEntry.getName();
                    InputStream inputStream = jarFile.getInputStream(jarEntry);
                    try (ByteArrayOutputStream byteArrayOutputStream =
                                 new ByteArrayOutputStream()) {
                        JarHelper.toBytes(inputStream, byteArrayOutputStream);
                        byte[] bytes = byteArrayOutputStream.toByteArray();
                        instance.initClassLoader(StringUtilsExt.replaceClassName(className), bytes);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return instance;
    }

    public static byte[] readJarsFile() {
        try {
            URL url = ClazzSource.class.getClassLoader().getResource("jar/dubbo-demo" +
                    "-interface-2.7.7.jar");
            FileInputStream jarFile = new FileInputStream(new File(url.getPath()));
            try (ByteArrayOutputStream byteArrayOutputStream =
                         new ByteArrayOutputStream()) {
                JarHelper.toBytes(jarFile, byteArrayOutputStream);
                return byteArrayOutputStream.toByteArray();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
